package com.tanhua.autoconfig.template;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.tanhua.autoconfig.properties.OssProperties;

import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

public class OssTemplate {
    private OssProperties properties;

    public OssTemplate(OssProperties properties){
        this.properties=properties;
    }
    /**
     * 文件上传
     * 1.文件名称
     * 2.输入流
     */
    public String upload(String filename, InputStream is){
        filename=new SimpleDateFormat("yyyy/MM/dd").format(new Date())+"/"+ UUID.randomUUID().toString()+filename.substring(filename.indexOf("."));
        String endpoint=properties.getEndpoint();
        String accessKeyId=properties.getAccessKey();
        String accessKeySecret=properties.getSecret();
        //创建Oss实例
        OSS oss = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        //填写Bucket名称和object完整路径，object完整路径不能包含Bucket名称
        oss.putObject(properties.getBucketName(),filename,is);
        //关闭
        oss.shutdown();
        String url=properties.getUrl()+"/"+filename;
        return url;
    }
}
